<template>
  <el-container class="user-page">
    <el-aside width="270px">
      <el-container>
        <el-header>
          <el-button-group style="width: 100%">
            <el-button :type="switchType.dept ? 'primary' : ''" icon="el-icon-user" @click="changeType('dept')" style="width: 33%">按部门</el-button>
            <el-button :type="switchType.role ? 'primary' : ''" icon="el-icon-set-up" @click.stop="changeType('role')" style="width: 33%">按角色</el-button>
            <el-button :type="switchType.post ? 'primary' : ''" icon="el-icon-document-copy" @click="changeType('post')" style="width: 33%">按岗位</el-button>
          </el-button-group>
        </el-header>
        <el-main class="nopadding">
          <template v-if="switchType.dept">
            <el-tree ref="depts" class="menu" node-key="id" default-expand-all :data="tree.depts" :highlight-current="true" :expand-on-click-node="false" @node-click="deptClick" v-loading="loading.dept" style="padding: 10px"></el-tree>
          </template>
          <template v-else-if="switchType.role">
            <el-tree ref="roles" class="menu" node-key="roleId" default-expand-all :data="tree.roles" :highlight-current="true" @node-click="roleClick" v-loading="loading.role" style="padding: 10px"></el-tree>
          </template>
          <template v-else>
            <el-tree ref="posts" class="menu" node-key="postId" default-expand-all :data="tree.posts" :highlight-current="true" :expand-on-click-node="false" @node-click="postClick" v-loading="loading.post" style="padding: 10px"></el-tree>
          </template>
        </el-main>
      </el-container>
    </el-aside>
    <el-container>
      <el-header>
        <div class="left-panel">
          <el-button type="primary" icon="el-icon-plus" @click="add"></el-button>
		  <el-button type="warning" plain icon="jd-icon-upload"></el-button>
		  <el-button type="success" plain icon="jd-icon-download"></el-button>
          <el-button type="danger" plain icon="el-icon-delete" v-if="selection.length != 0" @click="batchDelete" v-auth="'system:user:remove'"></el-button>
          <!-- <el-button type="primary" plain :disabled="selection.length == 0">分配角色</el-button> -->
          <el-button type="primary" @click="resetUserPwd" plain v-if="selection.length != 0" v-auth="'system:user:resetPwd'">密码重置</el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">
            <el-input ref="searchInput" v-model="search.keyword" minlength="1" maxlength="20" placeholder="账号/姓名/手机" clearable></el-input>
            <el-button type="primary" icon="el-icon-search" @click="memberSearch"></el-button>
          </div>
        </div>
      </el-header>
      <el-main class="nopadding">
        <jdTable ref="table" :apiObj="apiObj" size="large" @selection-change="selectionChange" :params="params" stripe remoteSort remoteFilter>
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="账号" prop="userName" width="150" fixed="left"></el-table-column>
          <el-table-column label="姓名" prop="nickName" width="150" fixed="left"></el-table-column>
          <el-table-column label="手机号" prop="phone" width="150"></el-table-column>
          <el-table-column label="性别" prop="sex" align="center">
            <template #default="scope">
              <DictTag :options="dict.sex" :value="scope.row.sex"></DictTag>
            </template>
          </el-table-column>
          <el-table-column label="角色" prop="roleName" min-width="150"></el-table-column>
          <el-table-column label="部门" prop="deptName" min-width="200" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="状态" prop="status" width="100" align="center">
            <template #default="scope">
              <el-switch @change="changeStatus($event, scope.row)" :before-change="beforeChange" :model-value="scope.row.status" :active-value=0 :inactive-value=1 />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="150">
            <template #default="scope">
              <el-button-group>
                <el-button text type="primary" @click="memberModify(scope.row, scope.$index)" class="button">编辑</el-button>
                <el-popconfirm title="确定要删除吗？" @confirm="memberDelete(scope.row, scope.$index)">
                  <template #reference>
                    <el-button text type="primary" class="button">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>
        </jdTable>
      </el-main>
    </el-container>
  </el-container>

  <save-dialog v-if="dialog.save" ref="saveDrawer" @success="handleSuccess" @closed="dialog.save = false"></save-dialog>

</template>

<script>
import saveDialog from "./save"

export default {
  components: {
    saveDialog
  },
  data() {
    return {
      dict:{
        sex:[],
        status:[],
      },
      apiObj: this.$API.system.member.list,
      params: {},
      search: {
        userName: "",
        dept: "",
        role: "",
        post: ""
      },
      selection: [],
      dialog: {
        save: false,
        reset: false
      },
      // 角色
      roles: [],
      // 部门
      depts: [],
      // 岗位
      posts: [],
      switchType: {
        dept: true,
        post: false,
        role: false
      },
      loading: {
        dept: false,
        post: false,
        role: false
      },
      tree: {
        depts: [],
        posts: [],
        roles: []
      },
      switchStatus: false,
    }
  },
  mounted() {
    // 加载配置字典
    this.getDict();

    this.getGroup()
    // 部门列表
    this.getDepts()
    // 岗位列表
    this.getPosts()
    // 角色列表
    this.getRoles()
  },
  methods: {
    // 加载配置字典
    async getDict() {
      this.dict = {
        sex: await this.Dict.get("sys_user_sex"),
        status: await this.Dict.get("sys_normal_disable")
      }
    },
    // 按部门、按角色筛选数据
    changeType(val) {
      switch (val) {
        case 'dept':
            this.apiObj = this.$API.system.member.list
            this.switchType.dept = true
            this.switchType.post = false
            this.switchType.role = false
          break;
        case 'role':
            this.apiObj = this.$API.system.member.listByRole
            this.switchType.dept = false
            this.switchType.post = false
            this.switchType.role = true
          break;
        case 'post':
            this.apiObj = this.$API.system.member.listByPost
            this.switchType.dept = false
            this.switchType.post = true
            this.switchType.role = false
          break;
        default:
          break;
      }
    },
    // 加载部门列表
    async getDepts() {
      this.loading.dept = true
      var res = await this.$API.system.dept.tree.get()
      if (res.code == 200) {
        this.tree.depts = res.data
        this.loading.dept = false
      }
    },
    // 部门树点击事件
    deptClick(data) {
      var params = {
        dept: data.id
      }
      this.$refs.table.reload(params)
    },
    // 部门管理
    deptBtn() {
      this.$router.push("/system/dept")
    },
    // 加载角色列表
    async getRoles() {
      this.loading.role = true
      let params = {
        roleType: 1
      }
      var res = await this.$API.system.role.list.get(params)
      if (res.code == 200) {
        var roleList = res.data.rows.map((row) => {
          return {
            label: row.roleName,
            id: row.roleId
          }
        })
        this.dialog.roles = roleList
        this.tree.roles = [...roleList];
        var allNode ={label: '所有角色', id: ''}
        this.tree.roles.unshift(allNode);

        this.loading.role = false
      }
    },
    // 角色树点击事件
    roleClick(data) {
      var params = {
        roleId: data.id
      }
      this.$refs.table.reload(params)
    },
    // 加载岗位列表
    async getPosts() {
      this.loading.role = true
      var res = await this.$API.system.post.list.get()
      if (res.code == 200) {
        var postList = res.data.rows.map((row) => {
          return {
            label: row.postName,
            id: row.postId
          }
        })
        //this.dialog.posts = postList
        this.tree.posts = [...postList];
        var allNode ={label: '所有岗位', id: ''}
        this.tree.posts.unshift(allNode);

        this.loading.post = false
      }
    },
    // 岗位树点击事件
    postClick(data) {
      var params = {
        postId: data.id
      }
      this.$refs.table.reload(params)
    },
    // 获取所有角色,岗位,部门
    getGroup() {
      const getPostsRoles = async () => {
        const res = await this.$API.system.member.getPostRole.get()
        if (res.code === 200) {
          this.roles = res.roles
          this.posts = res.posts
        }
      }
      const getDept = async () => {
        var res = await this.$API.system.dept.tree.get()
        this.depts = res.data
      }
      getPostsRoles()
      getDept()
    },
    // 会员搜索
    memberSearch() {
      this.params.searchValue = this.search.keyword;
    },
    // 改变用户状态
    beforeChange(){
      this.switchStatus = true;
      return this.switchStatus;
    },
    // 改变用户状态
    async changeStatus(value, memberInfo) {
      if (this.switchStatus){
        const oldStatus = memberInfo.status
        memberInfo.status = value
        const res = await this.$API.system.member.changeStatus.put(memberInfo.memberId, memberInfo.status)
        if (res.code == 200 || res.code == 0) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
          memberInfo.status = oldStatus
        }
      }
    },
    //添加
    add() {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDrawer.open()
      })
    },
    //选择删除
    async select_del() {
      this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, "提示", {
        type: "warning"
      })
        .then(async () => {
          const loading = this.$loading()
          let ids = this.selection.map((item) => item.memberId)
          var res = await this.$API.system.member.delUser.delete(ids)
          if (res.code == 200) {
            //这里选择刷新整个表格 OR 插入/编辑现有表格数据
            this.$refs.table.getData()
            loading.close()
            this.$message.success("删除成功")
          } else {
            loading.close()
            this.$alert(res.message, "提示", { type: "error" })
          }
        })
        .catch(() => {})
    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection
    },
    // 会员编辑
    async memberModify(row) {
      let res = await this.$API.system.member.getUser.get(row.memberId)
      if (res.code == 200) {
        if (res.roleIds != null) {
          res.data.roleIds = res.roleIds[0]
        }
        this.dialog.save = true
        await this.$nextTick(() => {
          this.$refs.saveDrawer.open("edit").setData(res.data)
        })
      }
    },
    // 会员删除
    async memberDelete(row) {
      var res = await this.$API.system.member.delUser.delete(row.memberId)
      if (res.code == 200) {
        this.$refs.table.refresh()
        this.$message.success("删除成功")
      } else {
        this.$alert(res.msg, "提示", { type: "error" })
      }
    },
    // 重置用户密码
    async resetUserPwd() {
      this.$confirm(`确定要重置该用户的登录密码？`, "提示", {
        type: "warning"
      }).then(async () => {
        const loading = this.$loading()
        var res = await this.$API.system.member.resetUserPwd.put(this.selection[0].memberId, "")
        if (res.code == 200) {
          loading.close()
          this.$notify({
            title: "操作成功",
            message: "密码重置成功，新的密码为：" + res.msg,
            type: "success"
          })
        } else {
          loading.close()
          this.$alert(res.msg, "提示", { type: "error" })
        }
      })
    },
    //本地更新数据
    handleSuccess(data, mode) {
      if (mode == "add") {
        // this.$refs.table.tableData.unshift(data)
        this.$refs.table.getData()
      } else if (mode == "edit") {
        this.$refs.table.tableData
          .filter((item) => item.memberId === data.memberId)
          .forEach((item) => {
            Object.assign(item, data)
          })
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  height: 100%;
  padding-right: 24px;
}
.custom-tree-node .label {
  display: flex;
  align-items: center;
  height: 100%;
}
.custom-tree-node .label .el-tag {
  margin-left: 5px;
}
.custom-tree-node .do {
  display: none;
}
.custom-tree-node .do i {
  margin-left: 5px;
  color: #999;
}
.custom-tree-node .do i:hover {
  color: #333;
}

.custom-tree-node:hover {
  color: #409eff;
}
.custom-tree-node:hover .do {
  display: inline-block;
  animation: fadeIn;
  animation-duration: 1s;
}

.right-panel {
  ::v-deep .el-form-item {
    margin-bottom: 0;
    margin-right: 5px;
  }
  ::v-deep .el-form-item__label {
    font-size: 12px;
    font-weight: bold;
  }
}
</style>
